package com.base.controller.czb.czbadmin;

import com.alibaba.fastjson.JSONArray;
import com.base.controller.api.RedisCacheManager;
import com.base.controller.utils.CZB.CZBPayUtils;
import com.base.helper.LJSmsHelper;
import com.base.helper.VosHelper;
import com.base.po.czb.GasOrderH5read;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.service.CZB.GasOrderH5readService;
import com.base.service.CallbackinfoesService;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 *  @Date: 2020/4/16 14:03
 *  @Description:
 *  对czb订单的手动查询和插入
 */
@Controller
@RequestMapping("/gas")
public class H5OrderManualcallback {

    private final CallbackinfoesService callbackinfoesService;

    private final  SubscribersService subscribersService;

    private final UsersService usersService;

    private final GasOrderH5readService gasOrderH5readService;

    private final RedisCacheManager redisCacheManager;

    public H5OrderManualcallback(CallbackinfoesService callbackinfoesService, SubscribersService subscribersService, UsersService usersService,
                                 GasOrderH5readService gasOrderH5readService, RedisCacheManager redisCacheManager) {
        this.callbackinfoesService = callbackinfoesService;
        this.subscribersService = subscribersService;
        this.usersService = usersService;
        this.gasOrderH5readService = gasOrderH5readService;
        this.redisCacheManager = redisCacheManager;
    }

    @RequestMapping("/pushOrder")
    public @ResponseBody
    NetState CZBpush(HttpServletRequest request,String beginTime, String endTime,String mobile,String parentid) {

        NetState netState = new NetState();
        String result = CZBPayUtils.getPlatformOrder(new Date().getTime(), beginTime, endTime, 1, 10);
        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setJson(result);
        readOrder(beginTime,endTime,mobile,parentid);
        return netState;
    }


    @SuppressWarnings(value = "unchecked")
    public void readOrder(String beginTime, String endTime,String mobile,String parentid) {
        String result = CZBPayUtils.getPlatformOrder(new Date().getTime(), beginTime, endTime, 1, 10);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();
        if (code.equals("200")) {
            /**
             *  @Date: 2019/12/26 17:12
             *  @Description:
             *  开始解析订单->先从订单数量开始
             */
            Object totalRowObject = jsonObject.get("totalRow");
            Object orderArray = jsonObject.get("result");
            if (orderArray == null) {
                return;
            }
            JSONArray orderResult = JSONArray.parseArray(orderArray.toString());
            orderResult.forEach(item -> {
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(item.toString());
                //开始获取参数
                String orderId = jsonObject1.getString("orderId");
                String phone = jsonObject1.getString("phone");
                String orderDt = jsonObject1.getString("orderDt");
                String payDt = jsonObject1.getString("payDt");
                String gasName = jsonObject1.getString("gasName");
                String province = jsonObject1.getString("province");
                String city = jsonObject1.getString("city");
                String county = jsonObject1.getString("county");
                String gunNo = jsonObject1.getString("gunNo");
                String oilNo = jsonObject1.getString("oilNo");
                String amountPay = jsonObject1.getString("amountPay");
                String amountGun = jsonObject1.getString("amountGun");
                String orderStatusName = jsonObject1.getString("orderStatusName");
                String paySn = jsonObject1.getString("paySn");
                String litre = jsonObject1.getString("litre");
                //判断是否存在订单，若订单存在则直接下一个，否则进行存入数据
                GasOrderH5read gasOrderH5read = new GasOrderH5read();
                gasOrderH5read.setAmountgun(new BigDecimal(amountGun));
                gasOrderH5read.setAmountpay(new BigDecimal(amountPay));
                gasOrderH5read.setCity(city);
                gasOrderH5read.setCounty(county);
                gasOrderH5read.setGasname(gasName);
                gasOrderH5read.setGunno(Integer.parseInt(gunNo));
                gasOrderH5read.setOrderdt(orderDt);
                gasOrderH5read.setOrderstatusname(orderStatusName);
                gasOrderH5read.setOrderid(orderId);
                gasOrderH5read.setPhone(phone);
                gasOrderH5read.setProvince(province);
                gasOrderH5read.setOilno(oilNo);
                gasOrderH5read.setPaysn(paySn);
                gasOrderH5read.setIspaymoney(0);
                gasOrderH5read.setLitre(litre);
                /**
                 *  @Date: 2019/12/27 11:09
                 *  @Description:
                 *  截取字符串，获取手机号前4位和后4位
                 */
                String phoneA = phone.substring(0, 3);
                String phoneB = phone.substring(7, 11);

                List<GasOrderH5read> gasOrderH5readList = gasOrderH5readService.selectByOrderId(orderId);
                if (gasOrderH5readList.size() <= 0) {
                    gasOrderH5readService.insertSelective(gasOrderH5read);
                } else {
                    gasOrderH5read = gasOrderH5readList.get(0);
                }
                /**
                 *  @Date: 2019/12/27 10:05
                 *  @Description:
                 *  进入Redis中寻找用户
                 */
                try {
                        /**
                         *  @Date: 2019/12/27 9:56
                         *  @Description:
                         *  插入结束，此处进行判断是否是这个平台的单，Redis中有记录且这里属于这个平台，插入！
                         */
                        Subscribers subscribers=subscribersService.selectBySubscribers(mobile,parentid);
                        String userid = subscribers.getId();
                        String mobileA = mobile.substring(0, 3);
                        String mobileB = mobile.substring(7, 11);
                        if (mobileA.equals(phoneA) && mobileB.equals(phoneB)) {
                            if (gasOrderH5read.getIspaymoney().equals(0)) {
                                //查询用户
                                Users agent = usersService.selectByPrimaryKey(parentid);
                                Subscribers user = subscribersService.selectByPrimaryKey(userid);

                                if (user == null) {
                                 return;
                                }
                                BigDecimal money = (gasOrderH5read.getAmountgun().subtract(gasOrderH5read.getAmountpay())).multiply(new BigDecimal(-1)); // 需要扣除的费用
                                /**
                                 *  @Date: 2019/12/27 13:08
                                 *  @Description:
                                 *  更新油站为已支付
                                 */
                                gasOrderH5read.setIspaymoney(1);
                                gasOrderH5read.setParentid(user.getShopid());
                                gasOrderH5read.setUsermobile(user.getMobile());
                                int code1 = gasOrderH5readService.updateByPrimaryKeySelective(gasOrderH5read);
                                if (code1 > 0) {
                                    //执行扣除话费
                                    String payinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix() + user.getMobile()
                                            + "\",\"ownerType\":\"2\",\"money\":\"" + money + "\",\"memo\":\"" + user.getUsername()
                                            + "，用户油站购买油的扣费" + money + "元\"}");

                                    //发送短信
                                    String outMoney = money.multiply(new BigDecimal(-1)).toPlainString();
                                    String msg = "您" + gasOrderH5read.getOrderdt() + "在" + gasOrderH5read.getGasname() + "订单号：" + gasOrderH5read.getOrderid() + "。加油" + gasOrderH5read.getLitre() + "升，金额:" + gasOrderH5read.getAmountgun() + "元，扣除账户余额：" + outMoney + "元，实际支付：" + gasOrderH5read.getAmountpay() + "元。如有疑问请联系客服。谢谢";
                                    LJSmsHelper.sendSmsToGasPay(user.getMobile(), agent.getUsername(), msg);
                                }
                            }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            /**
             *  @Date: 2020/4/14 11:15
             *  @Description:
             *  对未读取完的订单继续读取
             */
            Integer totalRow = Integer.parseInt(totalRowObject.toString());
            int i = 0;  //循环次数
            if (totalRow / 10 == 0) {
                i = 0;
            } else {
                i = totalRow / 10;
            }
            for (int j = 2; j < i + 1; j--) {
                readOrderList(new Date().getTime(), beginTime, endTime, j, i,mobile,parentid);
            }
        }
        System.out.println("油站读取成功");
    }

    /**
     * @Date: 2020/4/14 10:42
     * @Description:
     */
    private void readOrderList(long time, String beginTime, String endTime, int pageno, int cycles,String mobile,String parentid) {
        System.out.println("当前读油站订单次数循环:" + cycles);
        String result = CZBPayUtils.getPlatformOrder(new Date().getTime(), beginTime, endTime, pageno, 10);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();
        if (code.equals("200")) {
            Object orderArray = jsonObject.get("result");
            if (orderArray == null) {
                return;
            }
            JSONArray orderResult = JSONArray.parseArray(orderArray.toString());
            orderResult.forEach(item -> {
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(item.toString());
                //开始获取参数
                String orderId = jsonObject1.getString("orderId");
                String phone = jsonObject1.getString("phone");
                String orderDt = jsonObject1.getString("orderDt");
                String payDt = jsonObject1.getString("payDt");
                String gasName = jsonObject1.getString("gasName");
                String province = jsonObject1.getString("province");
                String city = jsonObject1.getString("city");
                String county = jsonObject1.getString("county");
                String gunNo = jsonObject1.getString("gunNo");
                String oilNo = jsonObject1.getString("oilNo");
                String amountPay = jsonObject1.getString("amountPay");
                String amountGun = jsonObject1.getString("amountGun");
                String orderStatusName = jsonObject1.getString("orderStatusName");
                String paySn = jsonObject1.getString("paySn");
                String litre = jsonObject1.getString("litre");
                //判断是否存在订单，若订单存在则直接下一个，否则进行存入数据
                GasOrderH5read gasOrderH5read = new GasOrderH5read();
                gasOrderH5read.setAmountgun(new BigDecimal(amountGun));
                gasOrderH5read.setAmountpay(new BigDecimal(amountPay));
                gasOrderH5read.setCity(city);
                gasOrderH5read.setCounty(county);
                gasOrderH5read.setGasname(gasName);
                gasOrderH5read.setGunno(Integer.parseInt(gunNo));
                gasOrderH5read.setOrderdt(orderDt);
                gasOrderH5read.setOrderstatusname(orderStatusName);
                gasOrderH5read.setOrderid(orderId);
                gasOrderH5read.setPhone(phone);
                gasOrderH5read.setProvince(province);
                gasOrderH5read.setOilno(oilNo);
                gasOrderH5read.setPaysn(paySn);
                gasOrderH5read.setIspaymoney(0);
                gasOrderH5read.setLitre(litre);
                /**
                 *  @Date: 2019/12/27 11:09
                 *  @Description:
                 *  截取字符串，获取手机号前4位和后4位
                 */
                String phoneA = phone.substring(0, 3);
                String phoneB = phone.substring(7, 11);

                List<GasOrderH5read> gasOrderH5readList = gasOrderH5readService.selectByOrderId(orderId);
                if (gasOrderH5readList.size() <= 0) {
                    gasOrderH5readService.insertSelective(gasOrderH5read);
                } else {
                    gasOrderH5read = gasOrderH5readList.get(0);
                }

                /**
                 *  @Date: 2019/12/27 10:05
                 *  @Description:
                 *  进入Redis中寻找用户
                 */
                try {
                        /**
                         *  @Date: 2019/12/27 9:56
                         *  @Description:
                         *  插入结束，此处进行判断是否是这个平台的单，Redis中有记录且这里属于这个平台，插入！
                         */

                        if (gasOrderH5read.getIspaymoney().equals(1)){
                            return;
                        }

                        String mobileA = mobile.substring(0, 3);
                        String mobileB = mobile.substring(7, 11);
                        if (mobileA.equals(phoneA) && mobileB.equals(phoneB)) {
                            if (gasOrderH5read.getIspaymoney().equals(0)) {
                                Subscribers subscribers=subscribersService.selectBySubscribers(mobile,parentid);
                                //查询用户
                                String userid=subscribers.getId();
                                Users agent = usersService.selectByPrimaryKey(parentid);
                                Subscribers user= subscribersService.selectByPrimaryKey(userid);

                                if (user==null) {
                                    return;
                                }
                                BigDecimal money = (gasOrderH5read.getAmountgun().subtract(gasOrderH5read.getAmountpay())).multiply(new BigDecimal(-1)); // 需要扣除的费用
                                /**
                                 *  @Date: 2019/12/27 13:08
                                 *  @Description:
                                 *  更新油站为已支付
                                 */
                                gasOrderH5read.setIspaymoney(1);
                                gasOrderH5read.setParentid(user.getShopid());
                                gasOrderH5read.setUsermobile(user.getMobile());
                                int code1 = gasOrderH5readService.updateByPrimaryKeySelective(gasOrderH5read);
                                if (code1 > 0) {
                                    //执行扣除话费
                                    String payinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix() + user.getMobile()
                                            + "\",\"ownerType\":\"2\",\"money\":\"" + money + "\",\"memo\":\"" + user.getUsername()
                                            + "，用户油站购买油的扣费" + money + "元\"}");
                                    System.out.println("手动扣费成功:"+mobile);
                                    //发送短信
                                    String outMoney = money.multiply(new BigDecimal(-1)).toPlainString();
                                    String msg = "您" + gasOrderH5read.getOrderdt() + "在" + gasOrderH5read.getGasname() + "订单号：" + gasOrderH5read.getOrderid() + "。加油" + gasOrderH5read.getLitre() + "升，金额:" + gasOrderH5read.getAmountgun() + "元，扣除账户余额：" + outMoney + "元，实际支付：" + gasOrderH5read.getAmountpay() + "元。如有疑问请联系客服。谢谢";
                                    LJSmsHelper.sendSmsToGasPay(user.getMobile(), agent.getUsername(), msg);
                                }
                            }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        System.out.println("油站读取成功");
    }

}
